// components/DefineUploader/index.js
const { fileUpload, filePreview } = require('../../api/index');

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    label: { type: String, value: '图片' },
    maxCount: { type: Number, value: 1 },
    errorMsg: { type: String, value: '' },
    value: { type: String, observer(newVal) {
      setFileList.call(this, newVal);
    } }
  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async onDelete(event) {
      const { file } = event.detail;
      this.setData({ fileList: this.data.fileList.filter(_s => _s.fid !== file.fid ) }, () => {
        setResult.call(this, this.data.fileList);
      });
    },
    async afterRead(event) {
      const { file } = event.detail;
      const res = await fileUpload(file);
  
      const { fileList = [] } = this.data;
      fileList.push({ ...file, url: res.data.url, fid: res.data.fid });

      setResult.call(this, fileList);
      this.setData({ fileList });
    },
  }
})

//  加工 上传的数据
function setResult(fileList = []) {
      //  处理需要传递的参数 使其支持多文件上传
      let str = '';
      fileList.forEach(_s => str += _s.fid + ',');
      str = str.replace(/\,$/, '');
      //  设置上传数据
      this.triggerEvent("uploader", str);
}

//  处理回显的图片数据
function setFileList(str = '') {
  const arr = str ? str.split(',') : [];
  const result = arr.map(_s => {
    const item = { fid: _s, url: filePreview('/file/preview/' + _s) };
    return item; 
  }) || [];

  this.setData({ fileList: result });
}